<template>
  <div>
    <h2>自定义频道 WebSocket 测试</h2>

    <div>
      <input v-model="channel" placeholder="输入订阅频道" />
      <button @click="subscribeChannel">订阅频道</button>
    </div>

    <div>
      <input v-model="message" placeholder="输入消息..." />
      <button @click="sendMessage">发送消息</button>
    </div>

    <h3>收到的消息</h3>
    <ul>
      <li v-for="(msg, index) in messages" :key="index">{{ msg }}</li>
    </ul>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Client } from '@stomp/stompjs'

// 响应式数据
const channel = ref('default')
const message = ref('')
const messages = ref([])
const connected = ref(false)
let stompClient = null

// 生命周期钩子
onMounted(() => {
  // connectWebSocket()
})

// 连接 WebSocket
const connectWebSocket = () => {
  stompClient = new Client({
    brokerURL: `ws://${localStorage.getItem('localIP')}:6001/ws`,
    onConnect: () => {
      console.log('WebSocket 连接成功')
      connected.value = true
    },
    onStompError: (error) => console.error('STOMP 错误:', error)
  })

  stompClient.activate()
}

// 订阅频道
const subscribeChannel = () => {
  if (stompClient && connected.value) {
    const topic = `/topic/${channel.value}`
    stompClient.subscribe(topic, (message) => {
      console.log(message,"messagemessage");
      
      messages.value.push(`[${channel.value}] ${message.body}`)
    })
    console.log(`已订阅频道: ${topic}`)
  }
}

// 发送消息
const sendMessage = () => {
  if (stompClient && connected.value) {
    stompClient.publish({
      destination: `/app/channel/${channel.value}`,
      body: message.value
    })
    message.value = '' // 清空输入框
  }
}
</script>